/***
 * 获取初始化之后的字段名称
 */
function grid_getFieldName(appends,columns,fieldName){
    for(var i=0;i<columns.length;i++){
        var column = columns[i];
        if(column._column==fieldName){
            return column.field;
        }
    }
    for(var i=0;i<appends.length;i++){
        var append = appends[i];
        if(append==fieldName){
            return "h"+i;
        }
    }
    return undefined;
}

/***
 * 获取初始化之后的字段名称
 */
function grid_getField(appends,columns,row,fieldName){
    var _fieldName = grid_getFieldName(appends,columns,fieldName);
    if(typeof(_fieldName)=="undefined")
        return "";
    return row[_fieldName];
}
//扩展easyui
var grid_menu = null;
var grid_win = null;
$.extend($.fn.datagrid.methods, {
    //标题拖拽
    columnConfig: function(jq){
        return jq.each(function(){
            if(grid_menu==null) grid_menu = $('<div style="width:100px;display:none;"><div data-options="iconCls:\'icon-config-up\'">升序排列</div><div class="menu-sep" sort="1"></div><div data-options="iconCls:\'icon-config-down\'" sort="1">降序排列</div><div class="menu-sep" sort="1"></div><div data-options="iconCls:\'icon-config-sortnone\'">取消排序</div><div class="menu-sep" sort="1"></div><div data-options="iconCls:\'icon-config-hide\'">隐藏该列</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-all\'">配置所有列</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-save\'" config="1">保存配置</div><div class="menu-sep" config="1"></div><div data-options="iconCls:\'icon-config-refresh\'">恢复默认</div></div>').mousedown(panel_mousedown).appendTo('body');
            var target = this;//target 就是$("#gridTables")
            var targetOptions = $(target).datagrid('options');
            target.doAutoWidth = function(__grid,_loaded){
                var __options = __grid.datagrid("options");
                if(__options.autoWidth){
                    //自适应宽度
                    var gridWidth = __options.rownumbers ? 32:2;
                    var __columns = __options.columns[0];
                    for(var i=0;i<__columns.length;i++){
                        if(!__columns[i].hidden){
                            gridWidth += __columns[i].width;
                        }
                    }
                    if(gridWidth<250) gridWidth = 250;
                    else{
                        var winWidth = $(window).width();
                        if(gridWidth>winWidth){
                            gridWidth = winWidth;
                        }
                    }
                    __grid.datagrid("resize",{width:gridWidth});
                    if(__options._combox){
                        __grid[0].comboxPanel[0].doLocation(__grid[0].comboxPanel);
                    }
                    if(!_loaded)
                        grid_formatSelectedRow(__options,__grid);
                }
            };
            var panel = $(this).datagrid('getPanel');
            panel.attr("id",target.id);
            var cells = panel.find('div.datagrid-header td[field]');
            var _initColumns = targetOptions._initColumns;//默认列属性
            var defaultColumns = [];
            var _sortcolumn = targetOptions._sortcolumn;
            for(var i=0;i<_initColumns.length;i++){
                var _p = _initColumns[i];
                if(!_p.checkbox && _p._sort){
                    var cell=cells.filter("td[field='"+_p.field+"']:first").attr("sort","1");
                    cell.children().addClass("datagrid-sort");
                    if(typeof(_sortcolumn)!="undefined"){
                        for(var j=0;j<_sortcolumn.length;j++){
                            if(_sortcolumn[j].field==_p.field){
                                cell.children().removeClass("datagrid-sort-asc").removeClass("datagrid-sort-desc").addClass(_sortcolumn[j].up?"datagrid-sort-asc":"datagrid-sort-desc");
                                break;
                            }
                        }
                    }
                }
                var _c = {};
                for(var _o in _p){
                    _c[_o] = _p[_o];
                }
                defaultColumns.push(_c);
            }
            target.columnConfigTag = true;
            var divBody = panel.find("div.datagrid-body:last");
            if(!targetOptions._combox)
                divBody.css("overflow-x","auto");
            var scrollInterv = false;//拖拽滚动计时器
            var dragLocation = {x:0,y:0};//当前鼠标位置
            var dragStyle="";//拖拽原始位置Style
            function bodyDragingX(e){
                //拖拽至最左侧,右侧,横向滚动条跟随自动滚动
                if (dragLocation.x > divBody.width() + divBody.offset().left - 100) {
                    if (!scrollInterv)
                    //向右滚动
                        scrollInterv = window.setInterval(function () { divBody.scrollLeft(divBody.scrollLeft() + 3); }, 10);
                } else if (dragLocation.x < divBody.offset().left + 100) {
                    if (!scrollInterv)
                    //向左滚动
                        scrollInterv = window.setInterval(function () { divBody.scrollLeft(divBody.scrollLeft() - 3); }, 10);
                } else {
                    if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
                }
            }
            var grid_win_panel_show;
            var grid_win_panel_hide;
            function bodyDragingY(e){
                //拖拽至最上侧,下侧,横向滚动条跟随自动滚动
                var grid_win_panel = dragLocation.x < grid_win_panel_hide.offset().left - 33 ? grid_win_panel_show : grid_win_panel_hide;
                if (dragLocation.y > grid_win_panel.height() + grid_win_panel.offset().top - 20) {
                    if (!scrollInterv)
                    //向下滚动
                        scrollInterv = window.setInterval(function () { grid_win_panel.scrollTop(grid_win_panel.scrollTop() + 3); }, 10);
                } else if (dragLocation.y < grid_win_panel.offset().top + 20) {
                    if (!scrollInterv)
                    //向上滚动
                        scrollInterv = window.setInterval(function () { grid_win_panel.scrollTop(grid_win_panel.scrollTop() - 3); }, 10);
                } else {
                    if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
                }
            }
            function bodyDragingOver(){
                if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
            }
            cells.each(function(){
                //checkbox不允许拖拽
                //if($(this).find(":checkbox:first").length==1)
                //	return;
                var tdHeader = $(this);
                tdHeader.attr("_drop","1").draggable({
                    revert:true,
                    delay:200,
                    cursor:'pointer',
                    edge:5,
                    proxy:function(source){
                        var p = $('<div style="z-index:99999;position:absolute;border:2px dashed #999999;background-color: #efefef;color:#FF5500;"/>').appendTo('body');
                        p.html($(source).html());
                        p.css({width:p.width()+"px",height:p.height()+"px","overflow":"hidden"});
                        p.hide();
                        return p;
                    },
                    onBeforeDrag:function(e){
                        if(e.button!=0)return false;//如果不是左键不执行
                        e.data.startLeft = $(this).offset().left;
                        e.data.startTop = $(this).offset().top;
                    },
                    onStartDrag: function(e){
                        $(document).bind("mousemove", bodyDragingX).bind("mouseup",bodyDragingOver);
                        dragLocation = {x:0,y:0};
                        dragStyle = $(this).attr("style");
                        if(typeof(dragStyle)=="undefined")dragStyle="";
                        $(this).draggable('proxy').css({
                            left:-2000,
                            top:-2000
                        });
                    },
                    onStopDrag: function(e){
                        $(document).unbind("mousemove", bodyDragingX).unbind("mouseup",bodyDragingOver);
                    },
                    onDrag:function(e){
                        dragLocation = {x:e.pageX,y:e.pageY};
                        $(this).draggable('proxy').show().css({
                            left:e.pageX+15,
                            top:e.pageY+15
                        });
                        return false;
                    }
                }).droppable({
                    accept:'#'+target.id+' td[_drop]',//本grid拖拽
                    onDragOver:function(e,source){
                        $(source).draggable('proxy').css("color","#078A08");
                        var span = $(this).find(".floatToolX");
                        if(span.length==0){
                            var height = $(this).height();
                            $(this).append('<span class="floatToolX" width="'+$(this).width()+'" height="'+height+'" style="height:'+height+'px";left:0/>');
                            span = $(this).find(".floatToolX");
                        }
                        var left = $(this).offset().left;
                        var width = $(this).width()/2;
                        if(dragLocation.x > left + width){
                            //右侧
                            span.attr("style","height:"+span.attr("height")+"px;right:0");
                        }else{
                            //左侧
                            span.attr("style","height:"+span.attr("height")+"px;left:0");
                        }
                    },
                    onDragLeave:function(e,source){
                        $(source).draggable('proxy').css("color","#FF5500");
                        $(this).find(".floatToolX").remove();
                    },
                    onDrop:function(e,source){
                        var targetTd = $(this);
                        var span = targetTd.find(".floatToolX:first");
                        if(span.length>0){
                            span=span.first();
                            var fromField = $(source).attr('field');
                            var toField = targetTd.attr('field');
                            setTimeout(function(){
                                var left = span.attr("style").indexOf("left")!=-1;
                                var options = $(target).datagrid('options');
                                moveField(options.columns,fromField,toField,left);
                                options._grid_columns=undefined;
                                //方案1本地数据加载
                                span.remove();
                                $(target).datagrid("clearSelections");
                                if(left)
                                    $(source).attr("style",dragStyle).insertBefore(targetTd);
                                else
                                    $(source).attr("style",dragStyle).insertAfter(targetTd);
                                $(target).datagrid("loadData",$(target).datagrid("getData"));
                                grid_formatSelectedRow(options,$(target));
                                //方案2重新请求数据加载$(target).datagrid();$(target).datagrid("columnConfig");
                            },0);
                            $('#grid_float_div').remove();
                        }
                    }
                }).contextmenu(function(e){
                    e.preventDefault();
                    if(tdHeader.is("[sort]")){
                        grid_menu.children("div[sort]").show();
                    }else
                        grid_menu.children("div[sort]").hide();
                    if(typeof($(target).datagrid('options')._page)=="undefined"){
                        grid_menu.children("div[config]").hide();
                    }else
                        grid_menu.children("div[config]").show();
                    grid_menu.menu({
                        onClick : function(item) {
                            if(item.text=="升序排列" || item.text=="降序排列"){
                                var up = item.text=="升序排列";
                                var options = $(target).datagrid('options');
                                var _sortcolumn = options._sortcolumn;
                                if(typeof(_sortcolumn)=="undefined") _sortcolumn = [];
                                var exists = false;
                                var field = tdHeader.attr('field');
                                for(var i=0;i<_sortcolumn.length;i++){
                                    if(_sortcolumn[i].field==field){
                                        exists = true;
                                        break;
                                    }
                                }
                                if(exists){
                                    _remove(field,_sortcolumn);//最后排序追加至最后
                                }
                                _sortcolumn.push({field:field,up:up});
                                tdHeader.children().removeClass("datagrid-sort-asc").removeClass("datagrid-sort-desc").addClass(up?"datagrid-sort-asc":"datagrid-sort-desc");
                                options._sortcolumn = _sortcolumn;
                                options._sortcolumns = undefined;
                                $(target).datagrid("reload");
                            }else if(item.text=="取消排序"){
                                var options = $(target).datagrid('options');
                                var _sortcolumn = options._sortcolumn;
                                if(typeof(_sortcolumn)=="undefined"||_sortcolumn.length==0)return;
                                _remove(tdHeader.attr('field'),_sortcolumn);
                                tdHeader.children().removeClass("datagrid-sort-asc").removeClass("datagrid-sort-desc");
                                options._sortcolumns = undefined;
                                $(target).datagrid("reload");
                            }else if(item.text=="隐藏该列"){
                                var columns = $(target).datagrid('options').columns[0];
                                var existsShow = false;
                                var field = tdHeader.attr('field');
                                for(var i=0; i<columns.length; i++){
                                    var column = columns[i];
                                    if (!column.hidden && column.field != field){
                                        existsShow = true;
                                        break;
                                    }
                                }
                                if(existsShow){
                                    tdHeader.hide();
                                    $(target).datagrid('hideColumn', field);
                                    target.doAutoWidth($(target));
                                }else{
                                    $.messager.alert('系统提示','该列无法隐藏，至少得保证有一列显示!','error',function(){
                                        if($(target).datagrid('options')._combox) target.inputtext.focus();
                                    });
                                }
                            }else if(item.text=="配置所有列"){
                                var columns = $(target).datagrid('options').columns[0];
                                if(grid_win==null){
                                    $('body').append('<div id="grid_win"><div class="easyui-layout" data-options="fit:true"><div data-options="region:\'west\',border:false,collapsible:false" style="width:210px;border:none;overflow-x:hidden" title="显示列" id="grid_win_panel_show"></div><div data-options="region:\'center\'" style="border-top:none;border-bottom:none;text-align:center;" id="grid_win_center"><a href="javascript:void(0)" id="grid_win_all_hide" title="全部隐藏" style="width:80%" data-options="iconCls:\'layout-button-right\'"></a><br/><a href="javascript:void(0)" id="grid_win_all_show" style="width:80%;margin-top:15px;" title="全部显示" data-options="iconCls:\'layout-button-left\'"></a></div><div data-options="region:\'east\',border:false,collapsible:false" style="width:210px;overflow-x:hidden" title="隐藏列" id="grid_win_panel_hide"></div><div data-options="region:\'south\'" style="text-align:center;padding:5px;height:40px;border-bottom:none;border-left:none;border-right:none;"><a class="easyui-linkbutton" data-options="iconCls:\'icon-ok\'" href="javascript:void(0)" id="grid_win_save">保存</a><a class="easyui-linkbutton" data-options="iconCls:\'icon-cancel\'" href="javascript:void(0)" style="margin-left:15px;" id="grid_win_cancel">取消</a></div></div></div>');
                                    $('#grid_win').mousedown(panel_mousedown).children().layout();
                                    $('#grid_win_all_hide,#grid_win_all_show,#grid_win_save,#grid_win_cancel').linkbutton({onClick:function(e){
                                        if(this.id=='grid_win_all_hide'){
                                            $('#grid_win_panel_show div[itemField]').appendTo($('#grid_win_panel_hide'));
                                        }else if(this.id=='grid_win_all_show'){
                                            $('#grid_win_panel_hide div[itemField]').appendTo($('#grid_win_panel_show'));
                                        }else if(this.id=='grid_win_save'){
                                            //保存配置
                                            var win_grid_target = grid_get(grid_win[0].target_grid.id);
                                            var _cells = win_grid_target.datagrid('getPanel').find('div.datagrid-header td[field]');
                                            var _columns = win_grid_target.datagrid('options').columns[0];
                                            var newColumns = [];
                                            var tempDiv = $("<div></div>");
                                            var headTr = _cells.first().parent();
                                            $('#grid_win_panel_show div[itemField]').each(function(){
                                                var field = $(this).attr("itemField");
                                                for(var i=0;i<_columns.length;i++){
                                                    var c = _columns[i];
                                                    if(c.field==field){
                                                        c.hidden = false;
                                                        newColumns.push(c);
                                                        win_grid_target.datagrid('showColumn', field);
                                                        _cells.filter('[field="'+field+'"]:first').show().appendTo(tempDiv);//方案1
                                                    }
                                                }
                                            });
                                            if(newColumns.length==0){
                                                $.messager.alert('系统提示','无法保存，至少得保证有一列显示!','error',function(){
                                                    if($(target).datagrid('options')._combox) target.inputtext.focus();
                                                });
                                                return;
                                            }
                                            $('#grid_win_panel_hide div[itemField]').each(function(){
                                                var field = $(this).attr("itemField");
                                                for(var i=0;i<_columns.length;i++){
                                                    var c = _columns[i];
                                                    if(c.field==field){
                                                        c.hidden = true;
                                                        newColumns.push(c);
                                                        win_grid_target.datagrid('hideColumn', field);
                                                        _cells.filter('[field="'+field+'"]:first').hide().appendTo(tempDiv);//方案1
                                                    }
                                                }
                                            });
                                            grid_win.window('close');
                                            var options=win_grid_target.datagrid('options');
                                            options.columns[0] = newColumns;
                                            options._grid_columns=undefined;
                                            //方案1本地数据加载
                                            tempDiv.children().appendTo(headTr);
                                            win_grid_target.datagrid("clearSelections");
                                            win_grid_target.datagrid("loadData",win_grid_target.datagrid("getData"));
                                            win_grid_target[0].doAutoWidth(win_grid_target);
                                            //方案2重新请求数据加载win_grid_target.datagrid();win_grid_target.datagrid("columnConfig");
                                        }else if(this.id=='grid_win_cancel'){
                                            grid_win.window('close');
                                        }
                                    }});
                                }
                                grid_win_panel_show = $('#grid_win_panel_show');
                                grid_win_panel_hide = $('#grid_win_panel_hide');
                                if(grid_win==null){
                                    grid_win_panel_show.add(grid_win_panel_hide).contextmenu(function(e){
                                        e.preventDefault();
                                    });
                                }
                                var height = $(window).height()-100;
                                if(height<250) height = 250;
                                var borderColor = "";
                                borderColor = $('#grid_win_center').css("padding-top",(height/2-70)+"px").css("border-left-color");
                                var display="";
                                var hidden="";
                                for(var i=0;i<columns.length;i++){
                                    var column = columns[i];
                                    var row = column.checkbox ? '<input type="checkbox"/>' : column.title;
                                    if(column.hidden){
                                        hidden+='<div style="white-space: nowrap;position: relative;height:16px;padding:3px;width:204px;overflow:hidden;border-bottom:1px dashed '+borderColor+'" itemField="'+column.field+'">'+row+'</div>';
                                    }else{
                                        display+='<div style="white-space: nowrap;position: relative;height:16px;padding:3px;width:204px;overflow:hidden;border-bottom:1px dashed '+borderColor+'" itemField="'+column.field+'">'+row+'</div>';
                                    }
                                }
                                var divs = grid_win_panel_show.html(display).find("div");
                                divs = divs.add(grid_win_panel_hide.html(hidden).find("div"));
                                divs.draggable({
                                    revert:true,
                                    delay:200,
                                    cursor:'pointer',
                                    edge:5,
                                    proxy:function(source){
                                        var p = $('<div id="grid_float_div" style="z-index:99999;padding:5px;position:absolute;border:2px dashed #999999;background-color: #efefef;color:#FF5500;font-size:12px;"/>').appendTo('body');
                                        p.html($(source).html());
                                        p.css({width:p.width()+"px",height:p.height()+"px","overflow":"hidden"});
                                        p.hide();
                                        return p;
                                    },
                                    onBeforeDrag:function(e){
                                        if(e.button!=0)return false;//如果不是左键不执行
                                        e.data.startLeft = $(this).offset().left;
                                        e.data.startTop = $(this).offset().top;
                                    },
                                    onStartDrag: function(e){
                                        $(document).bind("mousemove", bodyDragingY).bind("mouseup",bodyDragingOver);
                                        dragLocation = {x:0,y:0};
                                        dragStyle = $(this).attr("style");
                                        if(typeof(dragStyle)=="undefined")dragStyle="";
                                        $(this).draggable('proxy').css({
                                            left:-2000,
                                            top:-2000
                                        });
                                    },
                                    onStopDrag: function(e){
                                        $(document).unbind("mousemove", bodyDragingY).unbind("mouseup",bodyDragingOver);
                                    },
                                    onDrag:function(e){
                                        dragLocation = {x:e.pageX,y:e.pageY};
                                        $(this).draggable('proxy').show().css({
                                            left:e.pageX+15,
                                            top:e.pageY+15
                                        });
                                        return false;
                                    }
                                }).droppable({
                                    accept:'div[itemField]',
                                    onDragOver:function(e,source){
                                        $(source).draggable('proxy').css("color","#078A08");
                                        var span = $(this).find(".floatToolY");
                                        if(span.length==0){
                                            var height = $(this).height();
                                            $(this).append('<span class="floatToolY" width="'+$(this).width()+'" height="'+height+'" style="margin-left:3px;height:'+height+'px";left:0/>');
                                            span = $(this).find(".floatToolY");
                                        }
                                        var top = $(this).offset().top;
                                        var height = $(this).height()/2;
                                        if(dragLocation.y > top + height){
                                            //下侧
                                            span.attr("style","margin-left:3px;width:"+span.attr("width")+"px;bottom:0");
                                        }else{
                                            //上侧
                                            span.attr("style","margin-left:3px;width:"+span.attr("width")+"px;top:0");
                                        }
                                    },
                                    onDragLeave:function(e,source){
                                        $(source).draggable('proxy').css("color","#FF5500");
                                        $(this).find(".floatToolY").remove();
                                    },
                                    onDrop:function(e,source){
                                        if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
                                        var targetItem = $(this);
                                        var span = targetItem.find(".floatToolY:first");
                                        if(span.length>0){
                                            span=span.first();
                                            setTimeout(function(){
                                                var top = span.attr("style").indexOf("top")!=-1;
                                                span.remove();
                                                if(top)
                                                    $(source).attr("style",dragStyle).insertBefore(targetItem);
                                                else
                                                    $(source).attr("style",dragStyle).insertAfter(targetItem);
                                            },0);
                                        }
                                        $('#grid_float_div').remove();
                                    }
                                }).contextmenu(function(e){
                                    e.preventDefault();
                                    var targetPanel = $(this).parents('div[id]:first');
                                    $(this).appendTo($('#'+(targetPanel.attr('id')=='grid_win_panel_show' ? 'grid_win_panel_hide' : 'grid_win_panel_show')));
                                });
                                grid_win = $('#grid_win').window({
                                    title:'配置所有列',
                                    width:500,
                                    height:height,
                                    collapsible:false,
                                    minimizable:false,
                                    maximizable:false,
                                }).window('hcenter');
                                grid_win[0].target_grid = target;
                            }else if(item.text=="保存配置"){
                                $(target).datagrid("loading");
                                var options = $(target).datagrid('options');
                                var columns = options.columns[0];
                                var columnConfig = [];
                                var _sortcolumn = options._sortcolumn;
                                for(var i=0;i<columns.length;i++){
                                    var column = columns[i];
                                    var config = {f:column._column,w:column.width,h:column.hidden?"0":"1"};
                                    if(_sortcolumn){
                                        for(var j=0;j<_sortcolumn.length;j++){
                                            if(_sortcolumn[j].field==column.field){
                                                config.o = j+";"+(_sortcolumn[j].up ? "0" : "1");
                                                break;
                                            }
                                        }
                                    }
                                    columnConfig.push(config);
                                }
                                fy_api.ajax({
                                    url: "basis/saveColumnConfig.do?_t="+new Date().getTime(),
                                    data: {gridId:options._page+"$"+target.id,configInfo:columnConfig.length==0?"":JSON.stringify(columnConfig).replace(/\"/g, "'")},
                                    success: function(msg){
                                        $(target).datagrid("loaded");
                                        j_tip("配置保存成功！","success");
                                    }/*,error: function(){
                                     $(target).datagrid("loaded");
                                     $.messager.alert('系统提示','操作失败,服务器异常,请稍后重试或联系管理员!','error',function(){
                                     if(options._combox) target.inputtext.focus();
                                     });
                                     }*/
                                });
                            }else if(item.text=="恢复默认"){
                                $.messager.confirm('系统提示', '您确认清除该列表所有列配置信息?<br/><span style="color:red;">(点击确定自动删除列表配置)</span>', function(r){
                                    if (r){
                                        $(target).datagrid("loading");
                                        var options = $(target).datagrid('options');
                                        function do_reset(){
                                            options._sortcolumn = undefined;
                                            options._sortcolumns = undefined;
                                            options._grid_columns=undefined;
                                            //方案2重新加载
                                            options.columns[0] = defaultColumns;
                                            if(options._combox){
                                                target.inputtext.attr("_showSelected","1").trigger("focus");
                                            }
                                            //本地数据loadData必须打开本开代码,否则表头显示有问题$(target).datagrid("loadData",$(target).datagrid("getData"));
                                            $(target).datagrid().datagrid('columnConfig');
                                            target.doAutoWidth($(target),true);
                                            if(options._combox){
                                                $(target).datagrid("getPager").pagination({
                                                    layout:['first','prev','manual','next','last'],
                                                    beforePageText: '',//页数文本框前显示的汉字
                                                    afterPageText: '/{pages}页',
                                                    displayMsg: '共{total}条',
                                                });
                                            }
                                        }
                                        if(typeof(options._page)=="undefined"){
                                            do_reset();
                                        }else{
                                            fy_api.ajax({
                                                url: "basis/saveColumnConfig.do?_t="+new Date().getTime(),
                                                data: {gridId:options._page+"$"+target.id},
                                                success: function(msg){
                                                    do_reset();
                                                }/*,error: function(){
                                                 $(target).datagrid("loaded");
                                                 $.messager.alert('系统提示','操作失败,服务器异常,请稍后重试或联系管理员!','error',function(){
                                                 if(options._combox) target.inputtext.focus();
                                                 });
                                                 }*/
                                            });
                                        }
                                    }else{
                                        if(options._combox) target.inputtext.focus();
                                    }
                                });
                            }
                        }
                    }).menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                });
            });
            function _remove(field,cc){
                for(var i=0; i<cc.length; i++){
                    if (cc[i].field == field){
                        var c = cc[i];
                        cc.splice(i,1);
                        return c;
                    }
                }
                return null;
            }
            // move field to another location
            function moveField(columns,from,to,left){
                var cc = columns[0];
                var c = _remove(from,cc);
                if (c){
                    _insert(to,c,left);
                }
                function _insert(field,c,left){
                    var newcc = [];
                    for(var i=0; i<cc.length; i++){
                        if (cc[i].field == field){
                            if(left){
                                newcc.push(c);
                                newcc.push(cc[i]);
                            }else{
                                newcc.push(cc[i]);
                                newcc.push(c);
                            }
                        }else
                            newcc.push(cc[i]);
                    }
                    columns[0] = newcc;
                }
            }
        });
    },keyInit : function (jq) {
        return jq.each(function () {
            var grid = $(this);
            grid.datagrid('getPanel').panel('panel').attr('tabindex', 1).bind('keydown',{grid:grid}, grid_keydown );
        });
    }
});
function grid_keydown(e){
    var grid = e.data == null ? undefined : e.data.grid;
    if(typeof(grid)=="undefined" && this.type=="text") grid=grid_get($(this).attr("_grid_input"));
    if(grid.length==0)
        return;
    if(e.keyCode==27){
        e.preventDefault();
    }
    var options = grid.datagrid("options");
    if(options._combox){
        if(grid[0].comboxPanel.css("top")=="-2000px"){
            if(e.keyCode!=13){
                grid[0].comboxPanel[0].doLocation(grid[0].comboxPanel);
                var _input = grid[0].inputtext[0];
                if(_input.input_grid_search_time)clearTimeout(_input.input_grid_search_time);
                _input.input_grid_search_time= setTimeout(function() {
                    _input.gridSearch(grid,options);
                }, 10 );
            }
            if(e.keyCode==13 || e.keyCode==27 || (e.keyCode>36 && e.keyCode<41))
                return;
        }
    }
    switch (e.keyCode) {
        case 13: // enter
            var selected = grid.datagrid('getSelected');
            if (selected) {
                var _context_handle = options._context_handle;
                if(typeof(_context_handle)!="undefined"){
                    _context_handle[0].handle.call(grid[0],grid.datagrid("getRowIndex",selected),selected);
                }
            }else{
                if(options._combox){
                    input_grid_hide.call(grid[0].inputtext);
                }
            }
            break;
        case 27: // esc
            if(options._combox){
                input_grid_hide.call(grid[0].inputtext);
            }
            break;
        case 37: // left
            if(!this.showSelectedPanel){
                var options = grid.datagrid('getPager').data("pagination").options;
                var current = options.pageNumber;
                if(current>1)
                    grid.datagrid('gotoPage',current-1);
            }
            break;
        case 38: // up
            var selected = grid.datagrid('getSelected');
            var index = -1 ;
            if(selected)
                index = grid.datagrid('getRowIndex', selected);
            if (index > 0) {
                grid.datagrid('selectRow', index - 1);
            } else {
                var rows = grid.datagrid('getRows');
                grid.datagrid('selectRow', rows.length - 1);
            }
            break;
        case 39: // right
            if(!this.showSelectedPanel){
                var options = grid.datagrid('getPager').data("pagination").options;
                var current = options.pageNumber;
                var pages = Math.ceil(options.total/options.pageSize);
                if(current<pages)
                    grid.datagrid('gotoPage',current+1);
            }
            break;
        case 40: // down
            var selected = grid.datagrid('getSelected');
            var index = -1 ;
            var length = 0 ;
            if(selected){
                index = grid.datagrid('getRowIndex', selected);
                length = grid.datagrid('getRows').length;
            }
            if (index < length-1) {
                grid.datagrid('selectRow', index + 1);
            } else {
                grid.datagrid('selectRow', 0);
            }
            break;
        case 46: // del
            if(options._combox){
                var input = grid[0].inputtext[0];
                input.showPanel(input);//切换回查询列表
                if(input.input_grid_search_time)clearTimeout(input.input_grid_search_time);
                input.input_grid_search_time= setTimeout(function() {
                    input.gridSearch(grid,options);
                }, options.delay );
            }else{
                var selected = grid.datagrid('getSelected');
                if (selected) {
                    var _context_handle = options._context_handle;
                    if(typeof(_context_handle)!="undefined"){
                        for(var i=0;i<_context_handle.length;i++){
                            var handle = _context_handle[i];
                            if(handle.text=="删除"){
                                handle.handle.call(grid[0],grid.datagrid("getRowIndex",grid.datagrid("getSelected")),grid.datagrid("getSelected"));
                            }
                        }
                    }
                }
            }
            break;
        case 3: break;// shift
        case 9: break;// tab
        case 17: break;// ctrl
        case 18: break;// alt
        case 33:// pageup
            if(options.multiple){
                var input = grid[0].inputtext[0];
                input.showPanel(input);
                if(input.input_grid_search_time)clearTimeout(input.input_grid_search_time);
                input.gridSearch(grid,options);
            }
            break;
        case 34: // pagedown
            if(options.multiple){
                var input = grid[0].inputtext[0];
                input.showPanel(input,true);
            }
            break;
        case 35: break;// home
        case 36: break;// end
        default:
            if(options._combox){
                var input = grid[0].inputtext[0];
                if(e.altKey && options.multiple){
                    if(e.keyCode == 65){
                        //多选控件ALT+A,全选事件
                        input.selectAll(input);
                        return;
                    }
                    if(e.altKey && e.keyCode == 68){
                        //多选控件ALT+D,全不选事件
                        e.preventDefault();
                        input.clearText(input,true);
                        return;
                    }
                }
                input.showPanel(input);//切换回查询列表
                if(input.input_grid_search_time)clearTimeout(input.input_grid_search_time);
                input.input_grid_search_time= setTimeout(function() {
                    input.gridSearch(grid,options);
                }, options.delay );
            }else{
                if(e.altKey){
                    if(!options.singleSelect && e.keyCode == 65){
                        //多选grid,ALT+A,全选事件
                        grid.datagrid("checkAll");
                        return;
                    }
                    if(e.keyCode == 68){
                        //多选grid,ALT+D,全不选事件
                        e.preventDefault();
                        grid.datagrid("uncheckAll");
                        return;
                    }
                }
            }
            break;
    }
}
var _list_grid = [];
/**
 * 初始化grid
 参数grid:必须是jquery对象,且包含ID,grid主体
 initOptions:datagrid初始化参数,其中_table,columns为必填项_page填写则支持保存配置,不填则不支持配置
 */
function grid_init(grid,initOptions){
    var columns = initOptions.columns[0];
    grid.each(function(){
        var self = $(this);
        var grid_id = self.attr("id");
        if(typeof(grid_id)=="undefined"||grid_id=="")
            return;//必须有id属性
        var _initColumns = [];//默认列属性
        var grid_sum_str="";
        //转换适用后台的统一参数
        for(var i=0;i<columns.length;i++){
            var _c = {};
            var _p = columns[i];
            if(typeof(_p.width)=="undefined"){_p.width=100;}//默认100像素
            if(typeof(_p.align)=="undefined"){_p.align="center";}//默认标题居中
            if(typeof(_p.sortable)=="undefined"){_p.sortable="true";}//默认支持排序
            _p._sort = _p.sortable;
            _p.sortable = false;//原排序体验效果不好,使用右键排序,支持多列同时排序
            _p._column = _p.field;
            _p.field = "c"+i;
            _p.getFieldName = function(field){
                return grid_getFieldName(self.datagrid("options")._append,_initColumns,field);
            };
            _p.getFieldValue = function(row,field){
                return grid_getField(self.datagrid("options")._append,_initColumns,row,field);
            };
            for(var _o in _p){
                _c[_o] = _p[_o];
            }
            if(_p.sum){
                //需要合计
                grid_sum_str+=(grid_sum_str==""?"":",")+"sum("+_p._column+")"+" as "+_p.field;
            }
            _initColumns.push(_c);
        }
        function do_init(columnConfig){
            var _sortcolumn = [];
            if(columnConfig!=null && columnConfig!=""){
                //配置过列
                var columnConfig = eval(columnConfig);
                var initColumns = columns;
                var sortColumns = [];//排序
                columns = [];//计算的列配置
                for(var k=0;k<columnConfig.length;k++){
                    var cc = columnConfig[k];
                    for(var i=0;i<initColumns.length;i++){
                        var initColumn = initColumns[i];
                        if(initColumn._column==cc.f){
                            //匹配成功
                            if(initColumn._sort&&cc.o){
                                //存在排序
                                var order = cc.o.split(";");
                                sortColumns[parseInt(order[0])] = {field:initColumn.field,up:order[1]=="0"};
                            }
                            initColumn.width=cc.w;
                            initColumn.hidden=cc.h=="0";
                            columns.push(initColumn);
                            initColumns.splice(i,1);//移除
                            break;
                        }
                    }
                }
                for(var i=0;i<sortColumns.length;i++){
                    if(sortColumns[i]!=null){
                        _sortcolumn.push(sortColumns[i]);
                    }
                }
                for(var i=0;i<initColumns.length;i++){
                    //新加列未匹配成功,直接追加至最后
                    columns.push(initColumns[i]);
                }
            }
            var defaultOptions = {
                checkOnSelect: false,
                selectOnCheck: false,
                url: 'basis/findList.do',
                autoload: true,//false默认不加载数据,扩展
                //_page: "role_list",//必填,页面名称,如果多个grid使用同一配置该页面+id是区分条件
                //_table: "Tb_Role as o left join Tb_Company as company on o.companyId=company.companyId",//必填,查询table内容
                _append: [],//追加列,隐藏不显示作为条件使用,请勿与columns字段重复,例:["company.companyId","user.userId"]
                _sum: grid_sum_str,
                _initColumns: _initColumns,
                _sortcolumn: _sortcolumn,
                _exportTitle: "导出数据",//如果不导出直接写false
                type: "post",
                dataType: "json",
                border: false,
                loader:function(post_params,success,error){
                    var options = $(this).datagrid("options");
                    grid_params({options:options,post_params:post_params});
                    var grid_url = options.url+"?_t="+new Date().getTime()+(options.initUrlParam!=undefined?'&'+options.initUrlParam:'');//加入随机数,防止浏览器缓存
                    var autoload = options.autoload;
                    if(autoload && grid_url){
                        var selectedParam = false;
                        var searchArray = [];
                        if(options.multiple && this.inputtext[0].selectedItems=="init"){
                            //需要初始化
                            var _input = this.inputtext[0];
                            var searchValue = "";
                            var searchField = "";
                            if(_input.searchType=="id"){
                                searchField = options.idField;
                                searchValue = options.idInput.val();
                                searchArray = searchValue.substr(1,searchValue.length-2).split(",");
                            }else{
                                searchField = options.textField;
                                searchValue = options.textInput.val();
                                searchArray = searchValue.substr(1,searchValue.length-2).split(options.splitTag);
                            }
                            searchValue = fy_api.split;
                            for(var i=0;i<searchArray.length;i++){
                                searchValue+=searchArray[i]+fy_api.split;
                            }
                            selectedParam = {};
                            selectedParam["_c_"+searchField] = "∵"+searchValue;
                            grid_params({options:options,post_params:selectedParam,sumflag:false});
                        }
                        if(typeof(options.queryParamsFun)=="function")
                            this.inputtext[0].formatQueryParam(options,this.inputtext,post_params,selectedParam);

                        function __grid__load(self){
                            if(self.loading){
                                $(self).datagrid("loaded");
                                self.loading.abort();
                                return;
                            }
                            $(self).datagrid("clearSelections");
                            self.loading =fy_api.ajax({
                                data: post_params,
                                url: grid_url,
                                success: function(data){
                                    self.loading = false;
                                    if(options.multiple && self.inputtext[0].showSelectedPanel){
                                        $(self).datagrid("getPager").show();
                                        self.inputtext[0].showSelectedPanel = false;
                                    }
                                    var grid_data={total:data.records,rows:data.rows,footer:data.listSum==null?[]:data.listSum};
                                    success(grid_data);
                                    grid_formatSelectedRow(options,$(self));
                                }/*,error: function(e){
                                 self.loading = false;
                                 if(e.statusText!="abort"){
                                 $.messager.alert('系统提示','<b style="font-size:14px;">数据加载失败,服务器异常,请稍后重试或联系管理员!</b>','error');
                                 success({total:0,rows:[],footer:[]});
                                 }
                                 }*/
                            });
                        }

                        var self = this;
                        if(selectedParam){
                            //存在选中项需要初始化
                            fy_api.ajax({
                                data: selectedParam,
                                url: grid_url,
                                success: function(data){
                                    var _input = self.inputtext[0];
                                    var _idField = typeof(options.idField)=="undefined" ? undefined : self.getFieldName(options.idField);
                                    var _textField = self.getFieldName(options.textField);
                                    var _fieldName = _input.searchType=="id" ? _idField : _textField;
                                    var selectedItems = [];
                                    var list = data.rows;
                                    //根据初始化参数设置顺序
                                    for(var j=0;j<searchArray.length;j++){
                                        var _value = searchArray[j];
                                        for(var i=0;i<list.length;i++){
                                            if(_value==list[i][_fieldName]){
                                                selectedItems.push(list[i]);
                                                searchArray.splice(j,1);
                                                j--;
                                                list.splice(i,1);
                                                break;
                                            }
                                        }
                                    }
                                    for(var i=0;i<list.length;i++){
                                        selectedItems.push(list[i]);
                                    }
                                    _input.selectedItems = selectedItems;
                                    if(typeof(options.selected)=="function" && (searchArray.length>0 || list.length>0))//发生改变
                                        options.selected.call(self,$(_input),_input.selectedItems.length==0?null:_input.selectedItems);
                                    _input.formatSelected.call(_input,options.idInput,options.textInput,_idField,_textField);
                                    if(_input.showSelectedPanel){
                                        //初始化直接显示已选列表
                                        var grid = $(self);
                                        success({total:selectedItems.length,rows:selectedItems,footer:[]});
                                        grid_formatSelectedRow(grid.datagrid("options"),grid,true);
                                        grid.datagrid("getPager").hide();
                                    }else
                                        __grid__load(self,options);
                                }/*,error: function(e){
                                 self.inputtext[0].selectedItems = [];
                                 __grid__load(self,options);
                                 }*/
                            });
                        }else{
                            if(options.multiple && self.inputtext[0].showSelectedPanel){
                                //初始化直接显示已选列表
                                var grid = $(self);
                                var selectedItems = self.inputtext[0].selectedItems;
                                success({total:selectedItems.length,rows:selectedItems,footer:[]});
                                grid_formatSelectedRow(grid.datagrid("options"),grid,true);
                                grid.datagrid("getPager").hide();
                            }else{
                                __grid__load(self,options);
                            }
                        }
                    }else{
                        success({total:0,rows:[],footer:[]});
                    }
                },
                fit:true,
                loadMsg: "数据加载中，请稍后...",
                rownumbers: true,
                showFooter: true,
                pagination: true,
                singleSelect: true,
                pageSize: 20,
                pageList: [10, 20, 30],
                //bind数据成功重新设置拖动对象
                onLoadSuccess: function (data) {
                }
                /*,grid_init: function(grid,loaded){
                 //grid加载完成事件
                 },
                 pagebuttons: [{
                 iconCls:'icon-add',
                 text:'新增',
                 handler:function(){

                 }
                 }],
                 rowStyler: function(index,row){
                 if(this.getFieldValue && this.getFieldValue(row,"o.roleName")=="超级系统管理员"){
                 //return "background-color:red";
                 }
                 }
                 */
            };
            if(!initOptions.singleSelect){
                //多选
                initOptions.onBeforeSelect = function(index,row){
                    $(this).datagrid("clearSelections");
                };
                initOptions.onBeforeUnselect = function(){
                    return false;
                }
            }
            var searchDiv = [];
            if(typeof(initOptions.searchDiv)!="undefined"){
                //存在查询面板,初始化查询参数
                searchDiv = $(initOptions.searchDiv);
                if(searchDiv.length>0){
                    defaultOptions.queryParams = grid_searchParam(searchDiv);
                }
            }
            if(typeof(initOptions._context_handle)!="undefined"){
                if(!initOptions._combox){
                    //不是下拉控件,需要判断权限
                    var handles = new Array();
                    var handleCount = 0;
                    for(var i = 0;i < initOptions._context_handle.length; i++){
                        var handle = initOptions._context_handle[i];
                        if(typeof(handle.auth) == "undefined"){
                            //无需判断权限
                            handles.push(handle);
                            handleCount++;
                        }else{
                            var authPass = auth_validate(handle.auth);
                            if(authPass != 2){
                                //权限未加载,需要获取权限
                                handleCount++;
                                if(authPass == 1)
                                    handles.push(handle);
                            }
                        }
                    }
                    if(handleCount != initOptions._context_handle.length){
                        //存在需要判断权限的操作
                        initOptions.__context_handle = initOptions._context_handle;
                    }
                    initOptions._context_handle = handles;
                }
                initOptions.onRowContextMenu= function(e, index, row){
                    e.preventDefault();
                    if(index==-1)
                        return;
                    $(this).datagrid('clearSelections'); //取消所有选中项
                    $(this).datagrid('selectRow', index); //根据索引选中该行
                    var self_grid = $(this);
                    var self_gridOptions = $(this).datagrid("options");
                    if(self_gridOptions._menu == undefined) {
                        self_gridOptions._menu = $('<div style="width:100px;display:none;"></div>').appendTo('body');
                        var menuHtml = '';
                        for(var i=0;i<self_gridOptions._context_handle.length;i++){
                            var handle = self_gridOptions._context_handle[i];
                            if(i>0) menuHtml+='<div class="menu-sep"></div>';
                            menuHtml+='<div'+(handle.icon?' data-options="iconCls:\''+handle.icon+'\'"':'')+'>'+handle.text+'</div>';
                        }
                        self_gridOptions._menu.html(menuHtml).mousedown(panel_mousedown).menu({
                            onClick : function(item) {
                                for(var i=0;i<self_gridOptions._context_handle.length;i++){
                                    var handle = self_gridOptions._context_handle[i];
                                    if(handle.text==item.text && typeof(handle.handle)=="function"){
                                        handle.handle.call(self_grid[0],self_grid.datagrid("getRowIndex",self_grid.datagrid("getSelected")),self_grid.datagrid("getSelected"))
                                    }
                                }
                            }
                        })
                    }
                    if(self_gridOptions._context_handle.length > 0){
                        self_gridOptions._menu.menu('show', {
                            left : e.pageX,
                            top : e.pageY
                        });
                    }
                };
                if(initOptions._combox){
                    initOptions.onClickRow = function(index, row){
                        var self_grid = $(this);
                        initOptions._context_handle[0].handle.call(self_grid[0],index,row);
                    }
                }else{
                    initOptions.onDblClickRow = function(index, row){
                        var self_grid = $(this);
                        var self_gridOptions = self_grid.datagrid("options");
                        if(self_gridOptions._context_handle.length > 0)
                            self_gridOptions._context_handle[0].handle.call(self_grid[0],index,row);
                    }
                }
            }
            initOptions.columns[0] = columns;
            var gridOptions = $.extend({}, defaultOptions, initOptions);
            if(gridOptions._combox){
                //下拉grid,默认值
                gridOptions.autoload = false;
                gridOptions.autoWidth = true;
                gridOptions._exportTitle = false;
                gridOptions.border = 1;
            }
            if(gridOptions.autoWidth){
                //自适应宽度
                gridOptions.onResizeColumn=function(){
                    this.doAutoWidth($(this),true);
                };
                var gridWidth = gridOptions.rownumbers ? 32:2;
                for(var i=0;i<columns.length;i++){
                    if(!columns[i].hidden){
                        gridWidth += columns[i].width;
                    }
                }
                if(gridWidth<250) gridWidth = 250;
                else{
                    var winWidth = $(window).width();
                    if(gridWidth>winWidth){
                        gridWidth = winWidth;
                    }
                }
                gridOptions.width = gridWidth;
                gridOptions.fit = false;
            }
            var _grid = self.datagrid(gridOptions).datagrid("columnConfig").datagrid("keyInit")[0];
            _grid.getFieldName = function(field){
                return grid_getFieldName(_grid.datagrid("options")._append,_initColumns,field);
            };
            _grid.getFieldValue = function(row,field){
                return grid_getField(_grid.datagrid("options")._append,_initColumns,row,field);
            };
            _grid.search = function(reset){
                var param = {};
                if(searchDiv.length>0){
                    if(reset){
                        $("input[name][type='text']:not([notClear]),select[name]:not([notClear]),input[clear]",searchDiv).val("");
                        $("input[grid_multiple]",searchDiv).each(function(){
                            this.clearText(this);
                        });
                    }
                    param = grid_searchParam(searchDiv);
                }
                if(param==null) return;
                _grid.datagrid('load', param);
            };
            _grid = $(_grid);
            var _options = _grid.datagrid("options");
            _options.autoload = true;
            if(_options._exportTitle){
                //存在导出Excel
                _grid.datagrid('getPager').pagination({
                    buttons:[{
                        iconCls:'icon-config-excel',
                        title:'导出Excel',
                        handler:function(){
                            showLoading("正在导出,请稍候...");
                            var options = _grid.datagrid("options");
                            var post_params = options._post_params;
                            grid_params({options:options,post_params:post_params,exportflag:true});
                            var columnConfig = [];
                            var columns = options.columns[0];
                            for(var i=0;i<columns.length;i++){
                                var column = columns[i];
                                if(!column.hidden){
                                    columnConfig.push({t:column.title,w:column.width,c:column.field});
                                }
                            }
                            post_params.columns = JSON.stringify(columnConfig).replace(/\"/g, fy_api.split);
                            post_params.exportTitle_ = options._exportTitle;
                            window.location=fy_api.server_controller_path+"basis/excelExport.do?_t="+new Date().getTime()+urlEncode(post_params)+(options.initUrlParam!=undefined?'&'+options.initUrlParam:'');
                            setTimeout(function(){
                                hideLoading();
                            },2000);
                        }
                    }]
                });
            }
            if(searchDiv.length>0){
                searchDiv.find("input:visible,select:visible").unbind("keydown",search_keydown).bind("keydown",{_grid:_grid,searchDiv:searchDiv},search_keydown).first().focus().select();
            }
            if(typeof(initOptions.pagebuttons)!="undefined"){
                _grid.datagrid('getPager').pagination({
                    buttons:initOptions.pagebuttons
                });
            }
            if(typeof(initOptions.grid_init)=="function"){
                initOptions.grid_init(_grid,true);
            }
            if(gridOptions._combox){
                _grid.datagrid("getPager").pagination({
                    layout:['first','prev','manual','next','last'],
                    beforePageText: '',//页数文本框前显示的汉字
                    afterPageText: '/{pages}页',
                    displayMsg: '共{total}条',
                });
                _grid[0].comboxPanel = $("#_"+_grid.attr("id"));
                _grid[0].inputtext = _grid[0].comboxPanel[0].inputtext;
                _grid[0].comboxPanel[0].doLocation(_grid[0].comboxPanel);
                var _param = {};
                var _value = _grid[0].inputtext.val();
                if(_value!=""){
                    if(typeof(_options.searchField)!="undefined"){
                        var fieldName = "";
                        for(var _f = 0;_f<_options.searchField.length;_f++){
                            fieldName += (fieldName==""?"":",")+"_c_"+_options.searchField[_f];
                        }
                        _param[fieldName]=_value;
                    }else{
                        _param["_c_"+_options.textField]=_value;
                    }
                }
                _grid.datagrid("load",_param);
            }
            var _exists = false;
            for(var _i=0;_i<_list_grid.length;_i++){
                if(_list_grid[_i].id==grid_id){
                    _exists = true;
                    _list_grid[_i].grid = _grid;
                    break;
                }
            }
            if(!_exists)
                _list_grid.push({id:grid_id,grid:_grid});
        }
        if(typeof(initOptions._page)=="undefined"){
            do_init("");
        }else{
            showLoading();
            fy_api.ajax({
                url: "basis/findColumnConfig.do?_t="+new Date().getTime(),
                data: {gridId:initOptions._page+"$"+grid_id},
                success: function(columnConfig){
                    hideLoading();
                    do_init(columnConfig);
                }/*,error: function(){
                 hideLoading();
                 if(typeof(initOptions.grid_init)=="function"){
                 initOptions.grid_init(_grid,false);
                 }
                 $.messager.alert('系统提示','<b style="font-size:14px;">数据获取失败,服务器异常,请稍后重试或联系管理员!</b>','error');
                 }*/
            });
        }
    })
}

function search_keydown(event){
    //input查询键盘事件
    event.stopPropagation();
    if(event.keyCode==13){
        event.preventDefault();
        var _i = $(this);
        if(_i.attr("_stop")=="1"){
            _i.removeAttr("_stop");
            return;
        }
        _i.triggerHandler("blur");
        setTimeout(function(){
            var param = grid_searchParam(event.data.searchDiv);
            if(param!=null)
                event.data._grid.datagrid('load', param);
        },5)
    }
}

function grid_formatSelectedRow(__options,__grid,selectAll){
    //刷新选中标记
    if(__options.multiple){
        var __input = __grid[0].inputtext[0];
        var __panel = __grid.datagrid('getPanel');
        if(selectAll){
            //全选
            var trs = __panel.find("div.datagrid-body:last").find("tr").each(function(){
                $(this).find("td:visible:first").addClass("datagrid-row-selectedItem");
            });
        }else{
            __panel.find("td.datagrid-row-selectedItem").removeClass("datagrid-row-selectedItem");
            if(__input.selectedItems.length>0){
                var keyField = typeof(__options.idField)!="undefined" ? __options.idField : __options.textField;
                var _keyField = __grid[0].getFieldName(keyField);
                var _rows = __grid.datagrid("getData");
                _rows = typeof(_rows)=="undefined" ? [] : _rows.rows;
                var trs = __panel.find("div.datagrid-body:last").find("tr");
                for(var i=0;i<_rows.length;i++){
                    var _row = _rows[i];
                    for(var j=0;j<__input.selectedItems.length;j++){
                        if(__input.selectedItems[j][_keyField]==_row[_keyField]){
                            trs.eq(i).find("td:visible:first").addClass("datagrid-row-selectedItem");
                            break;
                        }
                    }
                }
            }
        }
    }
}

function grid_params(params){
    //grid查询参数赋值
    if(typeof(params.sumflag)=="undefined") params.sumflag = true;
    var options = params.options;
    var post_params = params.post_params;
    grid_company_params(options, post_params);
    options._post_params = post_params;
    var gird_order_str=options._sortcolumns;
    if(typeof(gird_order_str)=="undefined"){
        gird_order_str="";
        var gird_order = options._sortcolumn;
        if(gird_order!=undefined && gird_order.length>0){
            for(var i=0;i<gird_order.length;i++){
                gird_order_str+=(gird_order_str==""?"":",")+gird_order[i].field+" "+(gird_order[i].up?"asc":"desc");
            }
        }
        if(typeof(options._order)!="undefined") gird_order_str += (gird_order_str==""?"":",")+options._order;
        options._sortcolumns=gird_order_str;
    }
    var grid_columns_str=options._grid_columns;
    var grid_append_str=options._grid_append;
    var grid_export_str=options._grid_export;
    if(typeof(grid_columns_str)=="undefined"){
        grid_columns_str="";
        grid_append_str="";
        grid_export_str="";
        var _cs = options.columns[0];
        for(var i=0;i<_cs.length;i++){
            var c = _cs[i];
            grid_columns_str+=(grid_columns_str==""?"":",")+c._column+" as "+c.field;
            if(typeof(c._sql)=="undefined")
                grid_export_str+=(grid_export_str==""?"":",")+c._column+" as "+c.field;
            else
                grid_export_str+=(grid_export_str==""?"":",")+"("+c._sql+") as "+c.field;
        }
        for(var i=0;i<options._append.length;i++){
            grid_append_str+=","+options._append[i]+" as h"+i;
        }
        options._grid_columns = grid_columns_str;
        options._grid_append = grid_append_str;
        options._grid_export = grid_export_str;
    }
    if(gird_order_str!="")gird_order_str="order by "+gird_order_str;
    post_params.order_ = gird_order_str;//排序
    if(params.exportflag){post_params.column_ = grid_export_str;post_params.append_="";}else{post_params.column_ = grid_columns_str;post_params.append_ = grid_append_str;}//隐藏追加列
    post_params.table_ = options._table;//表
    if(params.sumflag)post_params.sum_ = options._sum;//合计
}

function grid_company_params(options, post_params){
    var idFlag = options.companyId != undefined;
    if(idFlag || options.companyIds != undefined){
        var companyId = '_c_' + (idFlag ? options.companyId : options.companyIds);
        //企业权限
        if(fy_api.loginUser != undefined){
            if(fy_api.loginUser.sysData == 0) return;
            var value;
            if(idFlag){
                value = '∵' + fy_api.loginUser.companyIds.replace(/,/g,fy_api.split);
            }else{
                value = fy_api.split;
                var companyIdArray = fy_api.loginUser.companyIds.substr(1,fy_api.loginUser.companyIds.length-2).split(",");
                for(var i = 0; i < companyIdArray.length; i++){
                    value += ',' + companyIdArray[i] + ',' + fy_api.split;
                }
            }
            post_params[companyId] = value;
        }else{
            post_params[companyId] = '∵0';
        }
    }
}

function grid_get(gridId){
    //获取grid对象
    for(var i=0;i<_list_grid.length;i++){
        var gridItem = _list_grid[i];
        if(gridItem.id == gridId)
            return gridItem.grid;
    }
}

function grid_searchParam(searchDiv){
    //获取输入查询参数
    var param = {};
    $("input[name],select[name]",searchDiv).each(function(){
        var value = $(this).val();
        if(value!=""){
            if(!checkText(this)){
                param = null;
                return false;
            }
            if($(this).is(":hidden,select") || ($(this).attr("like")==undefined && $(this).attr("nolike")!=undefined))
                value = "∵"+value;
            var date = $(this).attr("date");
            var prev = "_c_";
            if(date == "start")
                prev = "_s_";
            else if(date == "end")
                prev = "_e_";
            param[prev+$(this).attr("name")]=value;
        }
    });
    return param;
}

var _grid_temp_id = 0;

$.fn.extend({
    inputtree : function(options) {
        return $(this).each(function () {
            //加载树形控件图标
            var input = $(this);
            var height = input.outerHeight();
            if(!height) height = 25;
            var icon = $('<div class="icon-tree-search" style="height:'+height+'px;width:30px;overflow:hidden;cursor: pointer;" title="树形选择"></div>');
            icon.click(function(){
                if(typeof(options.beforeSearch)=="function"){
                    if(typeof(options.beforeSearch)=="function"){
                        if(!options.beforeSearch(input)){
                            input.attr("failed","1");
                            return;
                        }
                        input.removeAttr("failed");
                    }
                }
                var o = {
                    height: 400,
                    width: 300,
                    title: "树形选择",
                    iconCls: 'icon-form-info',
                    onClose: function(){
                        $("#j_tree_window").window("destroy");
                    }
                };
                $('<div id="j_tree_window"><div style="height:calc(100% - 40px);width:100%;overflow: auto;"><div id="j_tree_panel"><div style="margin-top:45%;text-align: center;"><div class="datagrid-mask-msg" style="margin-left:calc(50% - 60px);width:80px;display: block;position:static">正在加载中...</div></div></div></div><div class="border-color" style="border-left:none;border-right:none;border-bottom:none;height:34px;padding-top:5px;text-align: center;"><a class="easyui-linkbutton" id="btn_tree_save" iconCls="icon-save">确定</a><a style="margin-left:5px;" class="easyui-linkbutton c2" id="btn_tree_cancel" iconCls="icon-undo">取消</a>'+(options.multiple?'<a style="margin-left:5px;" class="easyui-linkbutton" id="btn_tree_all" iconCls="icon-accept">全选</a><a style="margin-left:5px;" class="easyui-linkbutton" id="btn_tree_unall" iconCls="icon-config-cancel">全不选</a>':'')+'</div></div>').appendTo("body:first").window(o);
                var treeWindow = $("#j_tree_window");
                $("#btn_tree_save").click(function(){
                    var tree_panel = $("#j_tree_panel");
                    if(typeof(tree_panel.tree)!="function"){
                        if(typeof(options.selected)=="function") options.selected.call(input[0],input,null);
                        if(idInput.length>0){
                            idInput.val("");
                        }
                        input.removeAttr("nolike").val("");
                    }else{
                        var node = tree_panel.tree(options.multiple?"getChecked":"getSelected");
                        if(node==null){
                            if(typeof(options.selected)=="function") options.selected.call(input[0],input,null);
                            if(idInput.length>0){
                                idInput.val("");
                            }
                            input.removeAttr("nolike").val("");
                        }else{
                            if(typeof(options.selected)=="function") options.selected.call(input[0],input,node);
                            if(options.multiple){
                                //多选
                                options.splitTag = typeof(options.splitTag)=="undefined"?fy_api.split:options.splitTag;
                                input[0].selectedItems = node;
                                input_formatSelected.call(input[0],options,7.5,idInput,textInput,idField,textField);
                                var grid = grid_get(input.attr("_grid_input"));
                                if(typeof(grid)!="undefined"){
                                    grid.datagrid("options")._searchtext = undefined;
                                }
                                input.val(getValue(input.attr("title")));
                            }else{
                                //单选
                                if(idInput.length>0){
                                    idInput.val(node[idField]);
                                }
                                input.attr("nolike","1").val(node[textField]);
                            }
                        }
                    }
                    $("#btn_tree_cancel").click();
                });
                $("#btn_tree_cancel").click(function(){
                    treeWindow.window("destroy");
                });
                $.parser.parse(treeWindow);
                var url = typeof(options.url) == "undefined" ? 'basis/findList.do' : options.url;
                url += "?_t="+new Date().getTime()+(options.initUrlParam!=undefined?'&'+options.initUrlParam:'');
                var post_params = {column_:"",append_:"",table_:options._table};
                var _cs = options.columns[0];
                var parentField = "";
                var textField = "";
                var idField = "";
                for(var i=0;i<_cs.length;i++){
                    var c = _cs[i];
                    if(c.field == options.textField){textField = "c"+i;}
                    if(c.field == options.idField){idField = "c"+i;}
                    if(c.field == options.parentField){parentField = "c"+i;}
                    if(typeof(c._sql)=="undefined")
                        post_params.column_+=(post_params.column_==""?"":",")+c.field+" as c"+i;
                    else
                        post_params.column_+=(post_params.column_==""?"":",")+"("+c._sql+") as c"+i;
                }
                for(var i=0;i<options._append.length;i++){
                    var c = options._append[i];
                    if(c == options.idField){idField = "h"+i;}
                    if(c == options.parentField){parentField = "h"+i;}
                    post_params.append_+=","+c+" as "+"h"+i;
                }
                input[0].formatQueryParam(options,input,post_params);
                grid_company_params(options,post_params);
                input[0].getFieldValue = function(row,field){
                    for(var i=0;i<_cs.length;i++){
                        var c = _cs[i];
                        if(c.field == field){
                            var value = row["c"+i];
                            return typeof(value)=="undefined"?"":value;
                        }
                    }
                    for(var i=0;i<options._append.length;i++){
                        var c = options._append[i];
                        if(c == field){
                            var value = row["h"+i];
                            return typeof(value)=="undefined"?"":value;
                        }
                    }
                    return "";
                };
                var idInput = {length:0};
                if(typeof(options.idInput)!="undefined") idInput = options.idInput;
                else idInput = input.prev("input:hidden");
                var textInput = {length:0};
                if(options.multiple){
                    //多选
                    if(typeof(options.textInput)!="undefined") textInput = options.textInput;
                    else textInput = input.next("input:hidden");
                }
                if(typeof(options._order)!="undefined")
                    post_params.order_ = "order by "+options._order;
                fy_api.ajax({
                    url: url,
                    data: post_params,
                    success: function(data){
                        var tree_panel = $("#j_tree_panel");
                        if(data==null||data.records==0){
                            tree_panel.find("div.datagrid-mask-msg").css({"background":"none","color":"red","font-weight":"bold","padding-left":"0px","width":"100px"}).html("不存在任何数据");
                        }else{
                            var rows = data.rows;
                            for(var i=0;i<rows.length;i++){
                                var row = rows[i];
                                row["id"] = row[idField];
                            }
                            function checkChangeChild(node,change){
                                tree_panel.tree(change, node.target);
                                var nodes = tree_panel.tree("getChildren",node.target);
                                for (var i = 0; i < nodes.length; i++) {
                                    checkChangeChild(nodes[i],change);
                                }
                            }
                            //加载树形控件数据
                            tree_panel[0].getFieldValue = input[0].getFieldValue;
                            tree_panel.tree({
                                checkbox: options.multiple,
                                cascadeCheck: false,
                                parentField:parentField,
                                textField:textField,
                                idField:idField,
                                formatter:options.treeformatter,
                                data:rows,
                                onDblClick: function(node){
                                    if(options.multiple){
                                        tree_panel.tree(node.checkState=='checked'?'uncheck':'check', node.target);
                                    }else{
                                        $("#btn_tree_save").click();
                                    }
                                },
                                onContextMenu:function(e,row){
                                    e.preventDefault();
                                    tree_panel.tree('select', row.target);
                                    if(typeof(row.children) != "undefined" && row.children.length>0){
                                        //存在子级显示展开收起
                                        tree_panel[0].menu.find("div[child='1']").show();
                                    }else{
                                        if(!options.multiple)
                                            return;
                                        tree_panel[0].menu.find("div[child='1']").hide();
                                    }
                                    tree_panel[0].menu.menu('show',{
                                        left: e.pageX,
                                        top: e.pageY
                                    });
                                },
                                onLoadSuccess:function(){
                                    tree_panel[0].menu = $('<div style="width:100px;display:none;">'+(options.multiple?'<div data-options="iconCls:\'icon-accept\'">全选</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-cancel\'">全不选</div><div class="menu-sep" child="1"></div>':'')+'<div data-options="iconCls:\'icon-config-add\'" child="1">展开全部</div><div class="menu-sep" child="1"></div><div data-options="iconCls:\'icon-config-delete\'" child="1">收起全部</div></div>').mousedown(panel_mousedown).appendTo('#j_tree_window').menu({
                                        onClick : function(item) {
                                            var node = tree_panel.tree("getSelected");
                                            if(node == null)
                                                return;
                                            if (item.text == "展开全部") {
                                                tree_panel.tree('expandAll', node.target);
                                            }else if (item.text == "收起全部") {
                                                tree_panel.tree('collapseAll', node.target);
                                            }else if (item.text == "全选") {
                                                checkChangeChild(node,"check");
                                            }else if (item.text == "全不选") {
                                                checkChangeChild(node,"uncheck");
                                            }
                                        }
                                    });
                                    if(options.multiple) {
                                        //多选
                                        $("#btn_tree_all").click(function () {
                                            var nodes = tree_panel.tree("getChildren");
                                            for (var i = 0; i < nodes.length; i++) {
                                                tree_panel.tree("check", nodes[i].target);
                                            }
                                            $("#btn_tree_save").click();
                                        });
                                        $("#btn_tree_unall").click(function () {
                                            var nodes = tree_panel.tree("getChecked");
                                            for (var i = 0; i < nodes.length; i++) {
                                                tree_panel.tree("uncheck", nodes[i].target);
                                            }
                                            $("#btn_tree_save").click();
                                        });
                                    }
                                    if(idInput.length==0)
                                        return;
                                    var initId = idInput.val();
                                    if(initId=="")
                                        return;
                                    if(options.multiple){
                                        //多选
                                        if(initId.substr(0,1)!=",")
                                            return;
                                        var initIds = initId.substr(1,initId.length-2).split(",");
                                        for(var i=0;i<initIds.length;i++){
                                            var node = tree_panel.tree('find', initIds[i]);
                                            if(node!=null)
                                                tree_panel.tree('check', node.target);
                                        }
                                    }else{
                                        var node = tree_panel.tree('find', initId);
                                        if(node!=null)
                                            tree_panel.tree('select', node.target);
                                    }
                                }
                            });
                        }
                    }
                })
            });
            input.addClass("inputtree").inputgrid(options).parent().append(icon);
        });
    },
    inputgrid : function(options) {
        return $(this).each(function(){
            var input = $(this);
            if(input.attr("readonly"))
                return input;
            input.attr("_value",input.val());
            var _fontWidth = 7.5;//多一位乘以宽度系数
            var _options =  $.extend({
                autoCheck:true,
                rownumbers:false,
                splitTag:fy_api.split
            }, options);
            _options.columns = [[]];
            var _columns = _options.columns[0];
            var columns = options.columns[0];
            for(var i=0;i<columns.length;i++){
                var _c = {};
                var _p = columns[i];
                for(var _o in _p){
                    _c[_o] = _p[_o];
                }
                _columns.push(_c);
            }
            var id = input.attr("id");
            if(typeof(id)=='undefined'){
                _options._page = undefined;//未赋值ID,无法启用配置
                input.attr("_grid_input",(_grid_temp_id++)+'_combogrid_temp');
            }else{
                input.attr("_grid_input",id+'_combogrid');
            }
            this.initOptions = _options;
            if(_options.multiple){
                input.attr("grid_multiple","1");
                this.selectedItems = [];
                this.formatSelected = function(idInput,textInput,idField,textField,textkeep){
                    input_formatSelected.call(this,_options,_fontWidth,idInput,textInput,idField,textField,textkeep);
                };
            }else{
                input.removeAttr("grid_multiple");
            }
            if(this.comboinit){
                //之前绑定过
                this.comboeventinit = undefined;
                if(typeof(this.tipSpan) != "undefined"){
                    this.tipSpan.remove();
                    var _next = input.next();
                    if(_next.attr("grid_hide")=="1"){
                        input.attr("name",_next.attr("name")).val(_next.val());
                        _next.remove();
                    }
                    input.removeAttr("placeholder");
                }
                $("#_"+input.attr("_grid_input")).remove();
                //input.unbind("keydown",grid_keydown).unbind("focus",input_grid_init).unbind("blur",input_grid_hide);
            }else{
                this.comboinit = true;
                this.resize = function(e){
                    var _input = e.data.input;
                    if(_input[0].resizeTime)clearTimeout(_input[0].resizeTime);
                    _input[0].resizeTime = setTimeout(function(){
                        var panel = $("#_"+_input.attr("_grid_input"));
                        var panelTop = panel.css("top");
                        if(panel.length>0 && typeof(panelTop)!="undefined" && panelTop!="-2000px"){
                            var grid = grid_get($(_input).attr("_grid_input"));
                            grid[0].doAutoWidth(grid,true);
                        }
                        if(typeof(_input[0].tipSpan) != "undefined"){
                            var _position = _input.position();
                            var _offset = _input.offset();
                            var _left = (_position.left>_offset.left?_position.left:_offset.left) + _input.outerWidth() - (_fontWidth*2);//左侧坐标
                            var _top = (_position.top>_offset.top?_position.top:_offset.top) + 3;//上侧坐标
                            _input[0].tipSpan.attr("left",_left).html(_input[0].selectedItems.length).css({"left":_left-_fontWidth*(_input[0].selectedItems.length.toString().length-1)+"px","top":_top+"px"});
                        }
                    },100);
                };
                $(window).bind("resize",{input:input},this.resize);
                input.bind("keydown",grid_keydown).bind("focus",input_grid_init).bind("blur",{blur:true},input_grid_hide).bind("click",function(){
                    var gridId = $(this).attr("_grid_input");
                    var _this = this;
                    var panel = $("#_"+gridId);
                    setTimeout(function(){
                        if($(_this).attr("failed")!="1"&&panel.css("top")=="-2000px"){
                            panel[0].doLocation(panel);
                            var grid = grid_get(gridId);
                            if(typeof(grid)!="undefined")
                                _this.gridSearch(grid,grid.datagrid("options"));
                        }
                    },50);
                });
            }
            if(typeof(_options.idInput)=="undefined" && input.prev().is("input:hidden") && typeof(_options.idField) != "undefined"){
                _options.idInput = input.prev();
            }
            if(_options.multiple && typeof(_options.textInput)=="undefined"){
                if(input.next().is("input:hidden"))
                    _options.textInput = input.next();
                else{
                    //未指定隐藏文本,用于查询,自动将隐藏值赋予name
                    if(typeof(input.attr('name'))!="undefined"){
                        _options.textInput = $('<input type="hidden" name="'+input.attr('name')+'" value="'+input.val()+'" grid_hide="1"/>').insertAfter(input);
                        input.removeAttr('name');
                    }else{
                        _options.textInput = $('<input type="hidden"/>').insertAfter(input);
                    }
                }
            }
            this.formatQueryParam = function(__options,__input,__post_params,__selectedParam){
                if(typeof(__options.queryParamsFun) == "function"){
                    var params = __options.queryParamsFun(__input);
                    for(var i=0;i<params.length;i++){
                        var param = params[i];
                        if(param.field == fy_api.split){
                            //自定义语句
                            param.like = true;
                            param.field += i;
                        }
                        var _value = (param.like?"":"∵")+param.value;
                        _value = (param.not?"∴":"")+_value;
                        var _field = "_c_"+param.field;
                        __post_params[_field] = _value;
                        if(__selectedParam) __selectedParam[_field] = _value;
                    }
                }
            };
            this.showPanel = function(_input,selected){
                if(selected){
                    //查看已选列表
                    if(!_input.showSelectedPanel){
                        var grid = grid_get($(_input).attr("_grid_input"));
                        if(typeof(grid)=="undefined")return;
                        var total = grid.datagrid("getData").total;
                        if(total<_input.selectedItems.length) total = _input.selectedItems;
                        grid.datagrid("clearSelections");
                        grid.datagrid("loadData",{total:total,rows:_input.selectedItems.slice(0),footer:[]});
                        grid_formatSelectedRow(grid.datagrid("options"),grid,true);
                        grid.datagrid("getPager").hide();
                        _input.showSelectedPanel = true;
                    }
                }else{
                    //切换查询列表
                    if(_input.showSelectedPanel){
                        var grid = grid_get($(_input).attr("_grid_input"));
                        _input.showSelectedPanel = false;
                        grid.datagrid("options")._searchtext = undefined;
                        grid.datagrid("getPager").show();
                    }
                }
            };
            if(_options.multiple){
                var _position = input.position();
                var _offset = input.offset();
                var _left = (_position.left>_offset.left?_position.left:_offset.left) + input.outerWidth() - (_fontWidth*2);//左侧坐标
                var _top = (_position.top>_offset.top?_position.top:_offset.top) + 3;//上侧坐标
                var _length = 0;
                var _value = input.val();
                if(_value!=""&&_value.substr(0,1)==_options.splitTag){
                    var valueArray = _value.substr(1,_value.length-2).split(_options.splitTag);
                    _value = "";
                    _length = valueArray.length;
                    for(var i=0;i<_length;i++){
                        _value+=(_value==""?"":",")+valueArray[i];
                    }
                    input.attr({placeholder:_value,title:_value}).val(_value);
                    this.searchType = "text";
                }else if(typeof(_options.idInput)!="undefined"){
                    input.attr({placeholder:_value,title:_value});
                    _value = _options.idInput.val();
                    if(_value!=""&&_value.substr(0,1)==","){
                        _length = _value.substr(1,_value.length-2).split(",").length;
                    }
                    this.searchType = "id";
                }
                if(_length>0) this.selectedItems = "init"; else this.selectedItems = [];//需要初始化
                this.tipSpan = $('<b title="[左键]查看已选(PageDown),[右键]全不选(Alt+D)" left="'+_left+'" style="position:absolute;cursor:pointer;left:'+(_left-_fontWidth*(_length.toString().length-1))+'px;top:'+_top+'px;z-index:10;font-size:12px;background-color:#FF5500;color:white;padding-left:3px;padding-right:3px;border-radius:5px;font-family:Microsoft YaHei">'+_length+'</b>');
                this.tipSpan[0].inputtext = $(this);
                this.selectAll = function(_input){
                    //全选
                    var grid = grid_get($(_input).attr("_grid_input"));
                    var options = grid.datagrid("options");
                    var post_params = _input.inputSearchParam($(_input),options);
                    grid_params({options:options,post_params:post_params,sumflag:false});
                    var grid_url = options.url+"?_t="+new Date().getTime()+(options.initUrlParam!=undefined?'&'+options.initUrlParam:'');//加入随机数,防止浏览器缓存
                    _input.formatQueryParam(options,$(_input),post_params);
                    var self = grid[0];
                    if(self.loading){
                        options._searchtext = undefined;
                        self.loading.abort();
                    }
                    grid.datagrid("loading");
                    self.loading = fy_api.ajax({
                        data: post_params,
                        url: grid_url,
                        success: function(data){
                            grid.datagrid("loaded");
                            self.loading = false;
                            if(data.rows==null || data.rows.length==0)
                                return;
                            var list = data.rows;
                            var _idField = typeof(options.idField)=="undefined" ? undefined : self.getFieldName(options.idField);
                            var _textField = self.getFieldName(options.textField);
                            if(_input.selectedItems.length==0){
                                _input.selectedItems = list;
                            }else{
                                var field = typeof(_idField)!="undefined" ? _idField : _textField;
                                for(var j=0;j<list.length;j++){
                                    var row = list[j];
                                    var _field = row[field];
                                    var exists = false;
                                    for(var i=0;i<_input.selectedItems.length;i++){
                                        if(_input.selectedItems[i][field]==_field){
                                            exists = true;
                                            break;
                                        }
                                    }
                                    if(!exists){
                                        _input.selectedItems.push(row);
                                    }
                                }
                            }
                            if(_input.showSelectedPanel){
                                var total = grid.datagrid("getData").total;
                                if(total<_input.selectedItems.length) total = _input.selectedItems;
                                grid.datagrid("clearSelections");
                                grid.datagrid("loadData",{total:total,rows:_input.selectedItems.slice(0),footer:[]});
                            }
                            grid_formatSelectedRow(options,grid,true);
                            if(typeof(options.selected)=="function")
                                options.selected.call(self,$(_input),_input.selectedItems.length==0?null:_input.selectedItems);
                            _input.formatSelected.call(_input,options.idInput,options.textInput,_idField,_textField,true);
                        }/*,error: function(e){
                         grid.datagrid("loaded");
                         self.loading = false;
                         if(e.statusText!="abort"){
                         $.messager.alert('系统提示','<b style="font-size:14px;">数据加载失败,服务器异常,请稍后重试或联系管理员!</b>','error');
                         }
                         }*/
                    });
                };
                this.tipSpan.mousedown(function(e){
                    e.preventDefault();
                    if (e.which == 1){
                        //查看已选
                        var _input = this.inputtext[0];
                        var _panel = $("#_"+$(_input).attr("_grid_input"));
                        if(_panel.length == 0){
                            //需要先初始化
                            _input.showSelectedPanel = true;
                            $(_input).trigger("focus");
                            return;
                        }
                        if(_panel.css("top")=="-2000px"){
                            $(_input).attr("_showSelected","1").trigger("focus");
                            _panel[0].doLocation(_panel);
                        }
                        _input.showPanel(_input,true);
                    }
                }).contextmenu(function(e){
                    e.preventDefault();
                    this.inputtext[0].clearText(this.inputtext[0],true);
                });
                $(this).parent().append(this.tipSpan);
                this.clearText = function(_input,keeptext){
                    _input.selectedItems = [];
                    var __grid = grid_get($(_input).attr("_grid_input"));
                    if(typeof(__grid)!="undefined"){
                        if(typeof(_input.initOptions.selected)=="function")
                            _input.initOptions.selected.call(__grid[0],$(_input),null);
                        var __options = __grid.datagrid("options");
                        if(keeptext&&typeof(__options._searchtext)!="undefined"&&__options._searchtext!="")
                            $(_input).val(__options._searchtext);
                        else
                            __options._searchtext = undefined;
                        grid_formatSelectedRow(__options,__grid);
                    }
                    _input.tipSpan.html("0").css("left",_input.tipSpan.attr("left")+"px");
                    $(_input).attr({placeholder:"",title:""});
                    if(_input.initOptions.idInput)
                        _input.initOptions.idInput.val("");
                    if(_input.initOptions.textInput)
                        _input.initOptions.textInput.val("");
                    $(_input).val("");
                }
            }else{
                this.clearText = function(_input,clearsearch){
                    var __grid = grid_get($(_input).attr("_grid_input"));
                    if(typeof(__grid)!="undefined") {
                        if (typeof(_input.initOptions.selected) == "function")
                            _input.initOptions.selected.call(__grid[0], $(_input), null);
                    }
                    if(_input.initOptions.idInput)
                        _input.initOptions.idInput.val("");
                    $(_input).val("");
                    if(clearsearch && typeof(__grid)!="undefined"){
                        __grid.datagrid("options")._searchtext = undefined;
                    }
                }
            }
        });
    }
});

function input_formatSelected(_options,_fontWidth,idInput,textInput,idField,textField,textkeep){
    var selectedIds = ",";
    var selectedTexts = "";
    var selectedTextsSplit = _options.splitTag;
    var hasId = typeof(idInput)!="undefined" && typeof(idField)!="undefined";
    for(var i=0;i<this.selectedItems.length;i++){
        var selectedItem = this.selectedItems[i];
        if(hasId)
            selectedIds += selectedItem[idField]+",";
        var value = selectedItem[textField];
        selectedTexts += (selectedTexts==""?"":",") + value;
        selectedTextsSplit += value + _options.splitTag;
    }
    if(hasId){
        idInput.val(this.selectedItems.length==0?"":selectedIds);
    }
    if(!textkeep) $(this).val("");
    $(this).attr({"placeholder":selectedTexts,"title":selectedTexts});
    textInput.val(this.selectedItems.length==0?"":selectedTextsSplit);
    this.tipSpan.html(this.selectedItems.length).css("left",parseInt(this.tipSpan.attr("left"))-_fontWidth*(this.selectedItems.length.toString().length-1)+"px");
}

function input_grid_hide(e){
    //隐藏grid方法
    var blur = e == undefined ? false : e.data == null ? false : e.data.blur;
    var grid = grid_get($(this).attr("_grid_input"));
    if(typeof(grid)=="undefined")
        return;
    if(blur){
        if(this.showSelectedPanel){
            this.showPanel(this);
        }
        if(this.initOptions.multiple){
            //多选
            $(this).val($(this).attr("placeholder"));
        }else if($(this).val()=="" && $(this).attr("_value")!=""){
            $(this).val($(this).attr("_value"));
            if(typeof(this.initOptions.selected)=="function"){
                this.initOptions.selected.call(grid[0],$(this),null);
            }
            $(this).attr("_value","").val("");
            if(typeof(this.initOptions.idField)!="undefined" && this.initOptions.idInput){
                this.initOptions.idInput.val("");
            }
        }else{
            $(this).attr("nolike","1");
            if(this.initOptions.autoCheck){
                $(this).val($(this).attr("_value"));
            }else if($(this).attr("_value")!=$(this).val()){
                $(this).removeAttr("nolike");
            }
        }
    }
    grid.datagrid("clearSelections");
    $("#_"+$(this).attr("_grid_input")).css({"top":"-2000px","left":"-2000px"});
}

function input_grid_init(e){
    //grid初始化,通常是input第一次focus
    var input = $(this);
    if(typeof(this.initOptions.beforeSearch)=="function"){
        if(!this.initOptions.beforeSearch(input)){
            input.attr("failed","1");
            return;
        }
        input.removeAttr("failed");
    }
    if(this.initOptions.multiple)
        input.val("");
    else if(this.initOptions.autoCheck)
        input.attr("_value",input.val());
    if(input.attr("_showSelected")=="1"){
        var param = grid_get(input.attr("_grid_input")).datagrid("options").queryParams;
        if(typeof(this.initOptions.searchField)!="undefined"){
            var fieldName = "";
            for(var _f = 0;_f<this.initOptions.searchField.length;_f++){
                fieldName += (fieldName==""?"":",")+"_c_"+this.initOptions.searchField[_f];
            }
            param[fieldName]="";
        }else{
            param["_c_"+this.initOptions.textField]="";
        }
        input.removeAttr("_showSelected");
        return;
    }
    if(!this.comboeventinit){
        this.comboeventinit = true;
        this.inputSearchParam = function(_input,_options){
            var param = {};
            var value = _input.val();
            if(value!=""){
                if(typeof(_options.searchField)!="undefined"){
                    var fieldName = "";
                    for(var _f = 0;_f<_options.searchField.length;_f++){
                        fieldName += (fieldName==""?"":",")+"_c_"+_options.searchField[_f];
                    }
                    param[fieldName]=value;
                }else{
                    param["_c_"+_options.textField]=value;
                }
            }
            return param;
        };
        this.gridSearch = function(grid,options){
            var param = grid[0].inputtext[0].inputSearchParam(grid[0].inputtext,options);
            var value = grid[0].inputtext.val();
            if(options._searchtext != value){
                grid.datagrid("load",param);
            }
            options._searchtext = value;
        };
        var defaultOptions = {delay: 200, loadMsg: "数据加载中，请稍后...", pagination:true};
        defaultOptions = $.extend(defaultOptions, this.initOptions);
        //初始化显示条数if(typeof(defaultOptions.pageSize)=="undefined"){defaultOptions.pageList=[20];defaultOptions.pageSize = 20};
        defaultOptions._combox = true;
        defaultOptions._context_handle = [{
            text: "选择",
            icon: "icon-accept",
            handle: function(index,row){
                if(defaultOptions.multiple){
                    //多选
                    var _input = this.inputtext.attr("_stop","1")[0];
                    setTimeout(function(){
                        $(_input).removeAttr("_stop");
                    },10);
                    if(index!=null){
                        var tr = $(this).datagrid('getPanel').find("div.datagrid-body:last").find("tr:eq("+index+")");
                        var _idField = typeof(defaultOptions.idField)=="undefined" ? undefined : this.getFieldName(defaultOptions.idField);
                        var _textField = this.getFieldName(defaultOptions.textField);
                        var td = tr.find("td:visible:first");
                        if(!td.is(".datagrid-row-selectedItem")){
                            td.addClass("datagrid-row-selectedItem");
                            _input.selectedItems.push(row);
                        }else{
                            var field = typeof(_idField)!="undefined" ? _idField : _textField;
                            var _field = row[field];
                            for(var i=0;i<_input.selectedItems.length;i++){
                                if(_input.selectedItems[i][field]==_field){
                                    _input.selectedItems.splice(i,1);
                                    break;
                                }
                            }
                            td.removeClass("datagrid-row-selectedItem");
                        }
                        if(typeof(defaultOptions.selected)=="function")
                            defaultOptions.selected.call(this,$(_input),_input.selectedItems.length==0?null:_input.selectedItems);
                        _input.formatSelected.call(_input,defaultOptions.idInput,defaultOptions.textInput,_idField,_textField);
                    }
                }else{
                    if(typeof(defaultOptions.selected)=="function"){
                        defaultOptions.selected.call(this,this.inputtext,row);
                    }
                    if(typeof(defaultOptions.idField)!="undefined" && defaultOptions.idInput){
                        defaultOptions.idInput.val(this.getFieldValue(row,defaultOptions.idField));
                    }
                    var _value = this.getFieldValue(row,defaultOptions.textField);
                    $(this.inputtext).val(_value).attr("_value",_value);
                    input_grid_hide.call(this.inputtext);
                }
            }
        }];
        defaultOptions._searchtext = input.val();
        var panel = $('<div style="top:-2000px;left:-2000px;" class="inputgrid-panel" id="_'+input.attr('_grid_input')+'">'+(defaultOptions.multiple?'<span class="inputgrid-all-select" style="cursor: pointer'+(defaultOptions.rownumbers?';left:32px':'')+'" title="鼠标[左键]:全选(Alt+A),[右键]全不选(Alt+D)"></span>':'')+'<table id="'+input.attr('_grid_input')+'"></table></div>');
        $("body").append(panel);
        panel.find("span.inputgrid-all-select").mousedown(function(e){
            e.preventDefault();
            if (e.which == 1){
                //全选
                panel[0].inputtext[0].selectAll(panel[0].inputtext[0]);
            }
        }).contextmenu(function(e){
            e.preventDefault();
            panel[0].inputtext[0].clearText(panel[0].inputtext[0],true);
        });
        panel[0].inputtext = input;
        panel[0].doLocation = function(_panel){
            var input = _panel[0].inputtext;
            var p = input.position();
            var o = input.offset();
            var left = (p.left>o.left?p.left:o.left);//左侧坐标
            var _panelWidth = _panel.width();
            var winWidth = $(window).width();
            if(left+_panelWidth<=winWidth){
                //左侧未超出
            }else if(left+input.outerWidth()-_panelWidth>0){
                //右侧未超出
                left = left+input.outerWidth()-_panelWidth;
            }else{
                //全部超出
                left = 0;
            }
            _panel.css({"top":((p.top>o.top?p.top:o.top)+input.outerHeight())+"px","left":left+"px"});
        };
        panel.mousedown(panel_mousedown);
        grid_init(panel.find("table:first"),defaultOptions);
    }else{
        var panel = $("#_"+input.attr("_grid_input"));
        panel[0].doLocation(panel);
        var grid = grid_get(input.attr("_grid_input"));
        if(this.input_grid_search_time)clearTimeout(this.input_grid_search_time);
        this.input_grid_search_time= setTimeout(function() {
            input[0].gridSearch(grid,grid.datagrid("options"));
        }, 10 );
    }
}

function panel_mousedown(e){
    e.preventDefault();
}

function j_showWin(options){
    j_closeWin();
    //弹窗事件
    var o = {
        height: $(window).height()-50,
        width: $(window).width()-30,
        repeater: true,//自动跳转至repeater进行转发(自动加载js与css)
        iconCls: 'icon-form-info',
        onClose: function(){
            $("#j_window").window("destroy");
        }
    };
    o = $.extend(o, options);
    if(o.repeater){
        o.url = "repeater.html?menuId=" + menuId + "&menuName=" + menuName + "&menuCode=" + menuCode + "&url=" + encodeURIComponent(o.url) + "&_t=" + new Date().getTime();
    }
    $('<div id="j_window"><iframe name="j_window" frameborder="0" src="'+o.url+'" style="width:100%;height:100%;" scrolling="auto"></iframe></div>').appendTo("body:first").window(o);
}

function j_closeWin(){
    var j_window = $("#j_window");
    if(j_window.length>0)
        j_window.window("destroy");
}
$.fn.window.defaults.minimizable=false;
$.fn.window.defaults.modal=true;
$.messager.defaults.closable=false;
$.fn.tree.defaults.loadFilter = $.fn.combotree.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().tree.options;
    var idField,
        textField,
        parentField;
    if (opt.parentField) {
        idField = opt.idField || 'id';
        textField = opt.textField || 'text';
        parentField = opt.parentField;
        var i,
            l,
            treeData = [],
            tmpMap = [];

        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idField]] = data[i];
        }

        for (i = 0, l = data.length; i < l; i++) {
            var row = data[i];
            var parentValue = row[parentField];
            if (parentValue != null && parentValue != 0 && tmpMap[parentValue] && row[idField] != parentValue) {
                if (!tmpMap[parentValue]['children'])
                    tmpMap[parentValue]['children'] = [];
                row['text'] = row[textField];
                tmpMap[parentValue]['children'].push(row);
            } else {
                row['text'] = row[textField];
                treeData.push(row);
            }
        }
        return treeData;
    }
    return data;
};
$.fn.treegrid.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().treegrid.options;
    var idField,
        parentField;
    if (opt.parentField) {
        idField = opt.idField || 'id';
        parentField = opt.parentField;
        var i,
            l,
            treeData = [],
            tmpMap = [];

        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idField]] = data[i];
        }

        for (i = 0, l = data.length; i < l; i++) {
            var row = data[i];
            var parentValue = row[parentField];
            if (parentValue != null && parentValue != 0 && tmpMap[parentValue] && row[idField] != parentValue) {
                if (!tmpMap[parentValue]['children'])
                    tmpMap[parentValue]['children'] = [];
                tmpMap[parentValue]['children'].push(row);
            } else {
                treeData.push(row);
            }
        }
        return treeData;
    }
    return data;
};
/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
var urlEncode = function (param, key, encode) {
    if(param==null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};

$(function(){
    var styleThemes = $("#styleThemes",parent.document);
    if(styleThemes.length==1)
        $("#s_styleThemes").attr("href","../"+styleThemes.attr("href"));
    else{
        styleThemes = $("#s_styleThemes",parent.document);
        if(styleThemes.length==1){
            $("#s_styleThemes").attr("href",styleThemes.attr("href"));
        }
    }
    setTimeout(function() {
        $("#help").click(function () {
            var o = {
                height: $(window).height() - 50,
                width: $(window).width() - 30,
                iconCls: 'icon-form-info',
                title: '菜单说明',
                onClose: function () {
                    $("#help_window").window("destroy");
                }
            };
            $('<div id="help_window"><div class="datagrid-mask-msg" style="margin-left:calc(50% - 60px);width:80px;display: block;position:absolute">正在加载中...</div></div>').appendTo("body:first").window(o);
            fy_api.ajax({
                url: "productLineMenu/get.do",
                data: {"keyId": menuId},
                success: function(menu){
                    $("#help_window").html(menu.helpRemark);
                }
            })
        })
    },500);
});
function page_loaded(){
    var saveForm = $("#saveForm");
    if(saveForm.length>0){
        setTimeout(function(){
            var allControls = saveForm.find("input:not(:button),select").not(":hidden,[readonly]");
            regNumberInput(allControls.attr("bindKeyDown","1").bind("keydown",function(event){saveKeyDown(saveForm,event,this)}));
            if(allControls.size()>0){
                var firstControl = allControls.first().focus();
                var onfocus = firstControl.attr("onfocus");
                if(typeof(onfocus)!="undefined"){
                    if(onfocus.length>12 && onfocus.substr(0,11)=="WdatePicker"){
                        if(onfocus.indexOf("{")!=-1){//}
                            var params = eval("["+onfocus.substring(onfocus.indexOf("{"),onfocus.lastIndexOf("}")+1)+"]");
                            params[0].el = firstControl[0];
                            WdatePicker(params[0]);
                        }else{
                            WdatePicker({el:firstControl[0]});
                        }
                    }else
                        eval(firstControl.attr("onfocus"));
                }else if(typeof(firstControl.select) == "function"){
                    firstControl .select(); //选中文字
                }
            }else{
                saveForm.find("span.div-item-info").each(function(){
                    $(this).attr("title",$(this).html());
                });
                $("#btnBack").attr("href","javascript:void(0);").focus();
            }
            if($("#addRow").not(":hidden").length==1){
                $(document).keydown(function(event){
                    if(event.altKey && event.keyCode==84){
                        //alt+T
                        $("#addRow").not(":hidden").click();
                    }
                });
            }
        },100)
    }
}
var number_max_length = 2;
var other_max_length = 4;
function regNumberInput(inputs){
    inputs.filter("[isNum]").not("[bindNumer]").attr("bindNumer","1").keyup(function(){
        var value = $.trim($(this).val());
        value = value.replace(/[^\d.]/g,"").replace(/^\./g,"").replace(/\.{2,}/g,".").replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        if(value.indexOf(".")!=-1){
            var a = value.split(".");
            var v = a[1];
            var _i = typeof($(this).attr("n_t"))=="undefined" ? number_max_length : other_max_length;
            if(v.length>_i){
                value = a[0] + "." + v.substr(0,_i);
            }
        }
        $(this).val(value);
        $(this).triggerHandler("change");
    }).change(function(){
        var value = $.trim($(this).val());
        value = value.replace(/[^\d.]/g,"").replace(/^\./g,"").replace(/\.{2,}/g,".").replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        if(value.indexOf(".")!=-1){
            var a = value.split(".");
            var v = a[1];
            var _i = typeof($(this).attr("n_t"))=="undefined" ? number_max_length : other_max_length;
            if(v.length>_i){
                value = a[0] + "." + v.substr(0,_i);
            }
        }
        $(this).val(value);
    })
}
function saveBindKeyDown(saveForm){
    var allControls = saveForm.find("input:not(:button),select").not(":hidden,[readonly]");//必须再查一次,因为可能存在新添加的控件
    regNumberInput(allControls.not("[bindKeyDown]").attr("bindKeyDown","1").bind("keydown",function(event){saveKeyDown(saveForm,event,this)}));
}

function saveKeyDown(saveForm,event,input){
    event.stopPropagation();
    if(event.altKey && event.keyCode==84){
        //alt+T
        $("#addRow").not(":hidden").click();
    }
    if(event.keyCode==13){
        event.preventDefault();
        if($(input).attr("_stop")=="1"){
            $(input).removeAttr("_stop");
            return;
        }
        setTimeout(function(){
            var allControls = saveForm.find("input:not(:button),select").not(":hidden,[readonly]");//必须再查一次,因为可能存在新添加的控件
            regNumberInput(allControls.not("[bindKeyDown]").attr("bindKeyDown","1").bind("keydown",function(event){saveKeyDown(saveForm,event,this)}));
            var idx = allControls.index (input) ; //获取当前焦点输入框所处的位置
            if ( idx == allControls.length - 1 ) // 判断是否是最后一个输入框
            {
                var btnSave = $("#btnSave");
                if(btnSave.length>0){
                    $(input).blur();
                    if(btnSave.attr("disabled") == "disabled")
                        return;
                    btnSave.click();
                }
            }else{
                var nextControl = allControls[ idx + 1 ];
                nextControl.focus() ; //设置焦点
                if(typeof(nextControl.select) == "function")
                    nextControl .select(); //选中文字
            }
        }, 5);
    }
}

function changeThemes(themes){
    $("#s_styleThemes").attr("href",themes);
    var j_window = $("#j_window");
    if(j_window.length==1 && j_window.is(":visible")){
        var changeThemesFun = j_window.find("iframe:first")[0].contentWindow.changeThemes;
        if(typeof(changeThemesFun)=="function"){
            changeThemesFun(themes);
        }
    }
}

function auth_validate(code){
    if(authArray == undefined){
        return 2;
    }
    for(var i = 0; i < authArray.length; i++){
        if(code == authArray[i]){
            return 1;
        }
    }
    return 0;
}